package com.bg.bgadmin.common.utils.excel;

import com.bg.bgadmin.common.utils.DateUtils;
import com.bg.bgadmin.common.utils.Reflections;
import com.bg.bgadmin.common.utils.excel.annotation.ExcelField;
import com.bg.bgadmin.modules.sys.utils.DictUtils;
import com.google.common.collect.Lists;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class ImportCsv {
    private static Logger log = LoggerFactory.getLogger(ImportCsv.class);

    private  InputStream in;
    /**
     * 导入文件
     *
     * @param fileName
     * @throws InvalidFormatException
     * @throws IOException
     */
    public ImportCsv(String fileName)
            throws InvalidFormatException, IOException {
        this(new File(fileName));
    }

    /**
     *
     * @param file
     * @throws InvalidFormatException
     * @throws IOException
     */
    public ImportCsv(File file)
            throws InvalidFormatException, IOException {
        this(file.getName(), new FileInputStream(file));
    }

    /**
     * 获取MultipartFile转换成数据流
     *
     * @param multipartFile
     * @throws InvalidFormatException
     * @throws IOException
     */
    public ImportCsv(MultipartFile multipartFile)
            throws InvalidFormatException, IOException {
        this(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
    }

    /**
     * 处理输入流
     * @param fileName
     * @param is
     * @throws InvalidFormatException
     * @throws IOException
     */
    public ImportCsv(String fileName, InputStream is)
            throws InvalidFormatException, IOException {

        if (StringUtils.isBlank(fileName)){
            throw new RuntimeException("导入文档为空!");
        }else if(fileName.toLowerCase().endsWith("csv")){
            this.in=is;
        }
    }

    public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException, IOException {
        List<Object[]> annotationList = Lists.newArrayList();
        // Get annotation field
        Field[] fs = cls.getDeclaredFields();
        for (Field f : fs){
            ExcelField ef = f.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==2)){
                if (groups!=null && groups.length>0){
                    boolean inGroup = false;
                    for (int g : groups){
                        if (inGroup){
                            break;
                        }
                        for (int efg : ef.groups()){
                            if (g == efg){
                                inGroup = true;
                                annotationList.add(new Object[]{ef, f});
                                break;
                            }
                        }
                    }
                }else{
                    annotationList.add(new Object[]{ef, f});
                }
            }
        }
        // Get annotation method
        Method[] ms = cls.getDeclaredMethods();
        for (Method m : ms){
            ExcelField ef = m.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==2)){
                if (groups!=null && groups.length>0){
                    boolean inGroup = false;
                    for (int g : groups){
                        if (inGroup){
                            break;
                        }
                        for (int efg : ef.groups()){
                            if (g == efg){
                                inGroup = true;
                                annotationList.add(new Object[]{ef, m});
                                break;
                            }
                        }
                    }
                }else{
                    annotationList.add(new Object[]{ef, m});
                }
            }
        }
        // Field sorting
        Collections.sort(annotationList, new Comparator<Object[]>() {
            public int compare(Object[] o1, Object[] o2) {
                return new Integer(((ExcelField)o1[0]).sort()).compareTo(
                        new Integer(((ExcelField)o2[0]).sort()));
            };
        });
        //log.debug("Import column count:"+annotationList.size());
        // Get excel data
        // Initialize
        List<String> headerList = Lists.newArrayList();
        for (Object[] os : annotationList){
            String t = ((ExcelField)os[0]).title();
            headerList.add(t);
        }
        String[] FILE_HEADER= headerList.toArray(new String[headerList.size()]);

        List<E> dataList = Lists.newArrayList();
        FileReader fileReader = null;
        CSVParser csvFileParser = null;
        //创建CSVFormat（header mapping）
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER);
        BufferedReader br= new BufferedReader(new InputStreamReader(this.in,"GBK"));
        //初始化 CSVParser object
        csvFileParser = new CSVParser(br, csvFileFormat);
        //CSV文件records
        List<CSVRecord> csvRecords = csvFileParser.getRecords();

        for (int i=1;i<csvRecords.size();i++) {
            CSVRecord csvRecord=csvRecords.get(i);
            E e = (E)cls.newInstance();
            StringBuilder sb = new StringBuilder();
            for (Object[] os : annotationList){
                String title = ((ExcelField)os[0]).title();
                Object val=csvRecord.get(title);
                if (val != null){
                    ExcelField ef = (ExcelField)os[0];
                    // If is dict type, get dict value
                    if (StringUtils.isNotBlank(ef.dictType())){
                        val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                        //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                    }
                    // Get param type and type cast
                    Class<?> valType = Class.class;
                    if (os[1] instanceof Field){
                        valType = ((Field)os[1]).getType();
                    }else if (os[1] instanceof Method){
                        Method method = ((Method)os[1]);
                        if ("get".equals(method.getName().substring(0, 3))){
                            valType = method.getReturnType();
                        }else if("set".equals(method.getName().substring(0, 3))){
                            valType = ((Method)os[1]).getParameterTypes()[0];
                        }
                    }
                    //log.debug("Import value type: ["+i+","+column+"] " + valType);
                    try {
                        if (valType == String.class){
                            String s = String.valueOf(val.toString());
                            if(StringUtils.endsWith(s, ".0")){
                                val = StringUtils.substringBefore(s, ".0");
                            }else{
                                val = String.valueOf(val.toString());
                            }
                        }else if (valType == Integer.class){
                            val = Double.valueOf(val.toString()).intValue();
                        }else if (valType == Long.class){
                            val = Double.valueOf(val.toString()).longValue();
                        }else if (valType == Double.class){
                             val = Double.valueOf(val.toString());
                        }else if (valType == Float.class){
                            val = Float.valueOf(val.toString());
                        }else if (valType == Date.class){
                            val = DateUtils.parseDate(val);
                        }else if (valType == BigDecimal.class){
                            val = new BigDecimal(val.toString());
                        }else{
                            if (ef.fieldType() != Class.class){
                                val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
                            }else{
                                val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                        "fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
                            }
                        }
                    } catch (Exception ex) {
                        log.info("Get cell value error: " + ex.toString());
                        val = null;
                    }
                    // set entity value
                    if (os[1] instanceof Field){
                        Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
                    }else if (os[1] instanceof Method){
                        String mthodName = ((Method)os[1]).getName();
                        if ("get".equals(mthodName.substring(0, 3))){
                            mthodName = "set"+ StringUtils.substringAfter(mthodName, "get");
                        }
                        Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
                    }
                }
                sb.append(val+", ");
            }
            dataList.add(e);
            log.debug("Read success:"+sb.toString());
        }
        br.close();
        return dataList;
    }
    public static void main(String[] args) throws Throwable {

//        ImportCsv importCsv=new ImportCsv("D:\\00交易汇总.csv");
//        importCsv.getDataList(User.class);

	}
}
